<?php
namespace common\helpers;
use Yii;

/**
 * redis 锁
 * Class Lock
 * @package common\helpers
 */
class Lock {


    const PREFIX = 'lock:';

    /**
     * @return mixed
     */
    public static function getRedis() {
        return Yii::$app->redis;
    }

    /**
     * 获取一个锁
     * @param string $name 锁名
     * @param integer $ttl 锁最大生存周期
     * @param integer $timeout 超时时间
     */
    public static function get($name, $ttl = 86400, $timeout = 0) {
        $key = self::PREFIX . $name;
        $redis = static::getRedis();
        if ($redis->set($key, 1, 'nx', 'ex' ,$ttl)) {
            return $name;
        } else {
            while ($timeout > 0) {
                sleep(1);
                $timeout--;
            }
            return false;
        }
    }

    /**
     * 删除锁
     * @param $name
     */
    public static function del($name)
    {
        $redis = static::getRedis();
        $redis->del(self::PREFIX . $name);
    }

    /**
     * 获取一个锁key值
     * @param $name
     * @return mixed
     */
    public static function getLockKeyValue($name)
    {
        $redis = static::getRedis();
        $value = $redis->get(self::PREFIX . $name);
        return $value;
    }
}